import { upload as _upload, download as _download, get, post } from '@/utils/Http';

/**
 * 文件上传
 * @param files 文件列表, 仅支持H5
 * @param paths 文件路径列表, files存在时, 忽略paths
 * @param attachCode 页面id
 * @param fieldId 文件字段名
 * @param sourceId 数据id
 * @param sourceType 数据类型
 * @returns {Promise<any[]>}
 */
export const upload = ({ paths, attachCode, fieldId, sourceId, sourceType, files }) => {
  const array = [];
  const formData = {
    attachCode: attachCode === '' ? 'default' : attachCode,
    fieldId: fieldId,
    sourceType: sourceType,
    sourceId: sourceId
  };
  if (sourceId) {
    const url = '/fileEndpoint/uploadAttach';
    if (files) {
      array.push(_upload({
        url,
        params: {
          files: files.map(file => ({
            name: 'files',
            uri: file
          })),
          formData
        }
      }));
    } else if (paths) {
      paths.forEach(file => {
        array.push(_upload({
          url,
          params: {
            name: 'files',
            path: file,
            formData
          }
        }));
      });
    }
  } else {
    const url = '/fileEndpoint/upload';
    if (files) {
      array.push(_upload({
        url,
        params: {
          files: files.map(file => ({
            name: 'files',
            uri: file
          })),
          formData
        }
      }));
    } else if (paths) {
      paths.forEach(file => {
        array.push(_upload({
          url,
          params: {
            name: 'files',
            path: file,
            formData
          }
        }));
      });
    }
  }

  return Promise.all(array);
};

/**
 * 下载
 * @param id 文件id
 * @param flag 未关联主数据时必须传0, 其他为空
 */
export const download = id => {
  const url = `/fileEndpoint/download?id=${id}`;
  return _download({ url });
};

/**
 * 获取文件列表
 * @param fieldId
 * @param attachCode
 * @param sourceId
 * @returns {*}
 */
export const fileList = ({ fieldId, attachCode, sourceId, sourceType }) => get({
  url: '/fileEndpoint/getFileInfosBySource',
  params: { fieldId, attachCode, sourceId, sourceType }
});
/**
 *
 * 删除附件
 * @param {*} param0
 * @returns
 */
export const delFile = params => post({
  url: `/fileEndpoint/removeFiles?ids=${params}`
});
